package top.anonyeast.config.interceptor;

import org.springframework.http.HttpMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.anonyeast.util.TokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Token拦截器
 *
 * @Author AnonyEast
 * @Date 2022-06-10
 * @Description
 */
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行OPTIONS请求
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            response.setStatus(response.SC_OK);
            return true;
        }
        //从请求头获取token
        String token = request.getHeader("Authorization");
        //验证token
        if (TokenUtil.verifyToken(token)) {
            return true;
        } else {
            response.setContentType("application/json;charset=UTF-8");
            response.sendError(401,"未登录");
            return false;
        }
    }
}
